import { useEffect, useState } from "react";
import "../../assets/scss/stores/storesadd.scss";
import { Button, Form, Input, TimePicker, Select, Upload, message } from "antd";
import { useNavigate, useParams } from "react-router-dom";
import dayjs from "dayjs";
// 上传
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";
import type { UploadChangeParam } from "antd/es/upload";
import { getadd, getmenu, getsingle } from "../../apis/stores/stores";
import type { RcFile, UploadFile, UploadProps } from "antd/es/upload/interface";
import moment from "moment";

const Repairs = (): JSX.Element => {

  const [form] = Form.useForm();
  let [fileList, setFileList]: any = useState([]);
  const navigate = useNavigate();
  const files = useParams();
  const [editid, seteditid]: any = useState(0);
   
  // console.log(6555555, files);
  // 上传守卫图片
  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("请上传 JPG/PNG 的图片!");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("图片大小不能超过2MB!");
    }
    return isJpgOrPng && isLt2M;
  };

  // 上传 logo
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();

  const handleChange: UploadProps["onChange"] = (
    info: UploadChangeParam<UploadFile>
  ) => {
    if (info.file.status === "uploading") {
      setLoading(true);
      return;
    }
    if (info.file.status === "done") {
      setImageUrl(info.file.response.data);
    }
  };

  const uploadButton = (
    <div>{loading ? <LoadingOutlined /> : <PlusOutlined />}</div>
  );
  const [servicesList, setServicesList] = useState([]);
  // 获取下拉
  const getdown = async () => {
    const res = await getmenu();
    console.log("嘿嘿", res);

    setServicesList(res.data.list);
  };
  // 上传图片
  const changeimg: UploadProps["onChange"] = (info: any) => {
    console.log(34343434, info);

    console.log(90,info.fileList);
    

    setFileList(info.fileList);
 
  };
  // 单体
  const getdetails = async () => {
     let _editid = Number(files.id);
    console.log(0,editid);
    if (_editid !== 0) {
      seteditid(_editid);
      const res: any = await getsingle({ id: _editid });
      console.log(222222222, res);
      // delete res.data.endTime;
       // delete res.data.startTime;
     if (res.errCode === 10000) {
        res.data.startTime = dayjs(res.data.startTime, "HH:mm");
        res.data.endTime = dayjs(res.data.endTime, "HH:mm");
        setImageUrl(res.data.logo);
        let imgs=  res.data.images.map((item: any) => {
          return {
            name: item.url,
            status: "done",
            val:item.url,
            url: "http://estate.eshareedu.cn/estate/upload/" + item.url,
          };
        });

        setFileList(imgs);
       

        form.setFieldsValue(res.data);
      }
    }
  };
  // 提交
  const onFinish = async (data: any) => {

    console.log(777,fileList);

console.log(data);
// return
    data.id=editid;
    
    data.logo = imageUrl;
    // data.images = imageUrlList;
    // 时间处理
    console.log(moment(data.startTime.$d).format("HH:mm"));
    data.startTime = moment(data.startTime.$d).format("HH:mm");
    data.endTime = moment(data.endTime.$d).format("HH:mm");
    console.log(data);

    data.images =fileList.map((item:any)=>({url:item.val ? item.val :item.response.data}))
    console.log(555666, editid);
    console.log(111111111112222222, data.images);
    
    // 添加
    // return;
    const res: any = await getadd(data);
    // console.log(111111111111111111, res);

    if (res.errCode === 10000) {
      if (Number(files.id) !== 0) {
        message.success("修改成功");
      } else {
        message.success("添加成功");
      }

      navigate("/home/stores");
    } else {
      message.error("添加失败！");
    }
  };
  // 手机号自定义验证
  const validatorMobile = (rule: any, value: string) => {
    console.log(rule);
    
    const phoneRegExp = /^1[3-9]\d{9}$/; // 定义手机号正则表达式
    switch (true) {
      case !value:
        return Promise.reject(new Error("请输入手机号"));
      case value.length < 11:
        return Promise.reject(new Error("请输入11位手机号"));
      case phoneRegExp.test(value):
        return Promise.resolve();
      default:
        return Promise.reject(new Error("请输入正确的手机号"));
    }
  };
  // 取消按钮
  const retreat = () => {
    navigate("/home/stores");
  };
  useEffect(() => {
    getdown();
    getdetails();
 
  }, []);
  return (
    <div className="storesadd">
      <div className="hd">门店添加</div>
      <div className="home">
        <Form
          form={form}
          className="content-input"
          name="basic"
          labelCol={{ span: 9 }}
          style={{ maxWidth: 1000 }}
          size="large"
          onFinish={onFinish}
          // onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <div className="content-left">
            <Form.Item
              label="店名"
              name="name"
              rules={[{ required: true, message: "请输入!" }]}
            >
              <Input placeholder="请输入" />
            </Form.Item>
            <Form.Item
              label="手机号"
              name="tel"
              rules={[{ required: true, validator: validatorMobile }]}
            >
              <Input placeholder="请输入" />
            </Form.Item>
            <div style={{ display: "flex", marginLeft: "110px" }}>
              <Form.Item label=" 营业时间" name="startTime">
                <TimePicker
                  changeOnBlur
                  placeholder="起始时间"
                  format="HH:mm"
                  style={{ width: "150px" }}
                />
              </Form.Item>
              <Form.Item name="endTime">
                <TimePicker
                  changeOnBlur
                  placeholder="结束时间"
                  format="HH:mm"
                  style={{ width: "150px", marginLeft: "15px" }}
                />
              </Form.Item>
            </div>
            <Form.Item
              name="services"
              label="服务范围"
              rules={[{ required: true, message: "请选择!" }]}
            >
              <Select placeholder="请输入" allowClear>
                {servicesList.map((item: any) => {
                  return (
                    <Select.Option key={item.id} value={item.name}>
                      {item.name}
                    </Select.Option>
                  );
                })}
              </Select>
            </Form.Item>
            <Form.Item
              label="店名"
              name="username"
              rules={[{ required: true, message: "请输入!" }]}
            >
              <Input placeholder="请输入" />
            </Form.Item>
            <Form.Item name="intro" label="门店介绍">
              <Input.TextArea />
            </Form.Item>
          </div>
          <div className="content-right">
            <Form.Item
              label="门店地址"
              name="address"
              rules={[{ required: true, message: "请输入!" }]}
            >
              <Input placeholder="请输入" />
            </Form.Item>
            <Form.Item label="门店logo"  valuePropName="imageUrl" name="logo">
              <Upload
                name="file"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action="http://estate.eshareedu.cn/estate/api/upload/add"
                beforeUpload={beforeUpload}
                onChange={handleChange}
                headers={{
                  Authorization: sessionStorage.getItem("token") || "",
                }}
              >
                {/* REACT_APP_IMG_URL */}
                {imageUrl ? (
                  <img
                    src={process.env.REACT_APP_IMG_URL + imageUrl}
                    alt="avatar"
                    style={{ width: "100%" }}
                  />
                ) : (
                  uploadButton
                )}
              </Upload>
            </Form.Item>
            <Form.Item label="门店图片22"  name="images">
              <Upload
                action="http://estate.eshareedu.cn/estate/api/upload/add"
                listType="picture"
                headers={{
                  Authorization: sessionStorage.getItem("token") || "",
                }}
                name="file"
                 fileList={fileList}
                // fileList={fileList}
                onChange={changeimg}
              >
                <Button style={{ background: "#409eff", color: "#fff" }}>
                  点击上传
                </Button>
              </Upload>
            </Form.Item>
            <div className="btn">
              <Button
                size="large"
                htmlType="submit"
                className="btn-left"
                type="primary"
              >
                添加
              </Button>
              <Button size="large" onClick={retreat} htmlType="button">
                取消
              </Button>

              <div></div>
            </div>
          </div>
        </Form>
      </div>
    </div>
  );
};
export default Repairs;
